#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author          : ricsy
@File            : assets.py.py
@Create Time     : 2025/6/18 04:47
@Last Modified   :
@Description     :
"""
from pathlib import Path

from theme_customizer.base import BaseCustomizer


class AssetManager(BaseCustomizer):
    """管理静态资源定制"""

    @property
    def _is_book_theme(self):
        return self.app.config.html_theme == self.SPHINX_BOOK_THEME_NAME

    @property
    def _is_enable_back_to_top_button(self):
        return self.app.config.html_theme_options.get("back_to_top_button", False)

    def apply(self):
        if self._is_book_theme:
            self._patch_book_theme_css()

    def _patch_book_theme_css(self):
        """修补 book 主题的 CSS"""
        if not self._is_enable_back_to_top_button:
            return
        # 由于 book 主题只有一个 CSS 样式文件，所以直接使用 next 方法
        # noinspection PyProtectedMember
        css_file = next(
            (
                f
                for f in self.app.builder._css_files
                if self.SPHINX_BOOK_THEME_NAME.replace("_", "-") in str(f.filename)
            ),
            None,
        )
        if css_file:
            self._remove_back_to_top_media_query(css_file)

    def _remove_back_to_top_media_query(self, css_file):
        """移除返回顶部按钮的媒体查询样式，使返回顶部按钮可以正常显示"""
        css_path = Path(self.app.builder.outdir) / css_file.filename
        remove_css_content = (
            "@media (min-width:1200px){#pst-back-to-top{display:none!important}}"
        )
        if css_path.exists():
            css_content = css_path.read_text(encoding="utf-8")
            patched = css_content.replace(remove_css_content, "")
            css_path.write_text(patched, encoding="utf-8")
